// 🎮 核心游戏引擎
interface GamePlugin {
  name: string;               // 插件唯一标识
  init?(engine: GameEngine): void; 
  destroy?(): void;           // 插件卸载时调用
  [event: string]: any;       // 事件处理函数
}

export class GameEngine {
  private plugins: Map<string, GamePlugin> = new Map();

  // 注册插件
  use(plugin: GamePlugin) {
    if (this.plugins.has(plugin.name)) {
      console.warn(`⚠️ 插件 [${plugin.name}] 已注册，忽略重复 use()`);
      return;
    }
    this.plugins.set(plugin.name, plugin);
    plugin.init?.(this);
    console.log(`✅ 插件 [${plugin.name}] 已加载`);
  }

  // 卸载插件
  eject(name: string) {
    const plugin = this.plugins.get(name);
    if (plugin) {
      plugin.destroy?.();
      this.plugins.delete(name);
      console.log(`🗑️ 插件 [${name}] 已卸载`);
    }
  }

  // 触发事件
  trigger(event: string, ...args: any[]) {
    for (const plugin of this.plugins.values()) {
      if (typeof plugin[event] === "function") {
        plugin[event](...args);
      }
    }
  }

  /* ====== 核心功能 ====== */
  start() {
    console.log("🚀 游戏启动！");
    this.trigger("onGameStart");
  }

  defeatEnemy() {
    console.log("💥 敌人被击败");
    this.trigger("onEnemyDefeated");
  }

  end() {
    console.log("🏁 游戏结束");
    this.trigger("onGameEnd");
  }
}

/* ========= 📦 插件实现 =========== */

// 日志插件
const Logger: GamePlugin = {
  name: "logger",
  init() {
    console.log("📝 日志插件已启动");
  },
  onGameStart() {
    console.log("[Logger] 游戏开始了");
  },
  onEnemyDefeated() {
    console.log("[Logger] 玩家击败了一个敌人");
  },
  onGameEnd() {
    console.log("[Logger] 游戏结束了");
  },
  destroy() {
    console.log("📝 日志插件已卸载");
  },
};

// 音乐插件
const Music: GamePlugin = {
  name: "music",
  onGameStart() {
    console.log("🎶 播放背景音乐");
  },
  onGameEnd() {
    console.log("🔇 停止背景音乐");
  },
};

// 计分插件
const Score: GamePlugin = {
  name: "score",
  score: 0,
  onEnemyDefeated() {
    this.score += 10;
    console.log(`🏆 当前分数: ${this.score}`);
  },
};

/* ========= 🚀 使用 =========== */
const engine = new GameEngine();

// 注册插件
engine.use(Logger);
engine.use(Music);
engine.use(Score);

// 游戏流程
engine.start();       // 游戏开始
engine.defeatEnemy(); // 打败敌人
engine.defeatEnemy(); // 再打败一个敌人

// 卸载插件
engine.eject("logger");
engine.defeatEnemy(); // 打败敌人
engine.defeatEnemy(); // 再打败一个敌人

// 结束游戏
engine.end();
